<script lang="ts">
export default {
  name: "Pie"
};
</script>

<script setup lang="ts">
import { ECharts } from "echarts";
import echarts from "/@/plugins/echarts";
import { onMounted, nextTick, ref } from "vue";
import { tryOnUnmounted, useTimeoutFn } from "@vueuse/core";
import { postProjectModule } from "/@/api/analysis";

import {
  addResizeListener,
  removeResizeListener
} from "element-plus/lib/utils/resize-event";

const pie = ref<HTMLElement | null>(null) as any;

let echartInstance: ECharts;

let seriesData = ref([]);

function initechartInstance(seriesData) {
  const echartDom = document.querySelector(".pie");
  if (!echartDom) return;
  // @ts-ignore
  echartInstance = echarts.init(echartDom);
  echartInstance.clear(); //清除旧画布 重新渲染

  echartInstance.setOption({
    color: ["#59a0ff", "#00e6ad", "#ffc500"],
    tooltip: {
      trigger: "item"
    },
    legend: {
      orient: "vertical",
      right: true
    },
    series: [
      {
        name: "信息",
        type: "pie",
        radius: "60%",
        center: ["40%", "50%"],
        data: seriesData,
        // [
        //   { value: 1079, name: "watchers" },
        //   { value: 1079, name: "star" },
        //   { value: 204, name: "forks" },
        //   { value: 3, name: "open_issues" }
        // ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  });
}

const initProjectNum = async () => {
  try {
    const { code, data } = await postProjectModule({});
    if (code === 200) {
      seriesData.value = data;
      nextTick(() => {
        initechartInstance(seriesData.value);
      });
    }
  } catch (err) {
    console.log(err);
  }
};

initProjectNum();

onMounted(() => {
  nextTick(() => {
    addResizeListener(pie.value, resetRender);
  });
  // useEventListener("resize", () => {
  //   console.log("resize");
  //   if (!echartInstance) return;
  //   useTimeoutFn(() => {
  //     echartInstance.resize();
  //   }, 180);
  // });
});

const resetRender = () => {
  if (!echartInstance) return;
  useTimeoutFn(() => {
    echartInstance.resize();
  }, 180);
};

tryOnUnmounted(() => {
  if (!echartInstance) return;
  echartInstance.dispose();
  echartInstance = null;
  removeResizeListener(pie.value, resetRender);
});
</script>

<template>
  <div ref="pie">
    <div class="title">
      <slot> </slot>
    </div>
    <div class="pie"></div>
    <p>自2022年2月15日培训后开始统计系统使用数据</p>
  </div>
</template>

<style scoped>
.title {
  font-size: 16px;
  font-weight: bold;
  padding-bottom: 10px;
}
.pie {
  width: 100%;
  height: 266px;
}
p {
  text-align: right;
  color: #7a7d83;
  font-size: 12px;
}
</style>
